﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCSService;
using System.Text;
using SCS.Core.Models;
using SCS.Core.ViewModels;
using System.Text.RegularExpressions;
using MvcReCaptcha;


namespace SCS.Core.Controllers
{
    public class PostController : BaseFontendController
    {

        #region "ListCategory"

        public ActionResult CategoryDetail(int id)
        {
            var type = Models.ModelsFontend.PostModel.GetCategory(id);
            ViewData["CategoryID"] = id;
            return View(type);
        }

        public StringBuilder GetListCategoryBuilder(int? id)
        {
            StringBuilder sb = new StringBuilder();
            return ListCategoryBuilder(ref sb, id);
        }

        public StringBuilder ListCategoryBuilder(ref StringBuilder sb, int? id)
        {
            int siteGuid=0;
            if (Request.Url.Host == "localhost")
            {
                //siteGuid = 2;
                if (Request.Url.ToString().Contains("favicon.ico"))
                {

                }
                else
                    siteGuid = DefaultSiteGuidGetter();
            }
            else
                siteGuid = Models.ConfigModel.GetWebsitebyDomain(DefaultHostGetter()).SiteGuid;

            List<SCSService.Post_Category> listCate = Models.ModelsFontend.PostModel.GetListCategoryByParentId(id);
            sb.Append("<ul>");
            foreach (var item in listCate)
            {
                if (DefaultHostGetter().Contains("localhost"))
                {
                    sb.Append("<li><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + "/Post/ListPost/" + item.CategoryID + "'>" + item.CategoryName + "</a></li>");
                }
                else
                {
                    sb.Append("<li><a href='/" + DefaultLanguageGetter() + "/Post/ListPost/" + item.CategoryID + "'>" + item.CategoryName + "</a></li>");
                }
               

                List<SCSService.Post_Category> listChild = Models.ModelsFontend.PostModel.GetListCategoryByParentId(item.CategoryID);
                if (listChild.Count() > 0)
                {
                    ListCategoryBuilder(ref sb, item.CategoryID);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        #endregion

        #region "Post"

        public ActionResult PostDetail(int id)
        {
            IntPage();
            return View();
        }

        [ChildActionOnly]
        public ActionResult PostView(int id)
        {
            var post = Models.ModelsFontend.PostModel.GetPostByID(id);
            ViewData["IDPost"] = id;

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/PostView", post);
        }

        public ActionResult ListPost(int? id)
        {
            IntPage();
            return View();   
        }

        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult ListPost(int? currentPage, int? pageSize, string gridAction, int? id)
        //{
        //    ViewData["ListCategory"] = GetListCategoryBuilder(null);

        //    //id đầu vào là typeId
        //    if (gridAction == "PageSizeChanged")
        //        currentPage = 1;

        //    if (currentPage == null && gridAction == "CurrentPageChanged")
        //    {
        //        string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
        //        currentPage = int.Parse(strCurrentPage);
        //    }
        //    else if (currentPage == null)
        //    {
        //        currentPage = 1;
        //    }

        //    if (pageSize == null)
        //    {
        //        pageSize = 10;
        //    }

        //    ViewData["currentPage"] = currentPage;


        //    var query = Models.ModelsFontend.PostModel.GetListPostByCategory(id).AsQueryable();
        //    int totalRows = query.Count();

        //    int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
        //    if (totalPages != 1)
        //    {
        //        //paging
        //        query = query.Skip(((int)currentPage - 1) * (int)pageSize)
        //                        .Take((int)pageSize);
        //    }

        //    UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize,null);

        //    var result = query.ToList();

        //    if (query.Count() > 0)
        //    {

        //    }

        //    if (totalRows == 0)
        //        return View(new List<SCSService.Post>());
        //    else
        //        return View(result);
        //}

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListBlogPosts(int? id)
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            //Id đầu vào là cateId
            int currentPage = 1;
            int pageSize = 5;

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            return ListBlogPosts(currentPage, pageSize, null, id);
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListBlogPosts(int? currentPage, int? pageSize, string gridAction, int? id)
        {

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            //id đầu vào là typeId
            if (gridAction == "PageSizeChanged")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                    pageSize = 5;
            }

            ViewData["currentPage"] = currentPage;


            var query = Models.ModelsFontend.PostModel.GetListPostByCategory(id, LanguageID, GetSiteGuid()).AsQueryable();
            int totalRows = query.Count();
            int totalPages = 0;
                totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);

            if (totalPages != 1)
            {
                //paging

               
               query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
               
            }

            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize, null);

            var result = query.ToList();

            if (query.Count() > 0)
            {

            }

            // Set up our ViewModel
            var viewModel = new ListPostViewModels
            {
                PostItem = result,
                PostCategory = id != null ? Models.ModelsFontend.PostModel.GetCategory((int)id) : null,
                currenPageValue = (int)currentPage
            };

            if (totalRows == 0)
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListBlogPosts", new ListPostViewModels());
            else
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListBlogPosts", viewModel);

        }

        public ActionResult PostToBlog()
        {
            IntPage();
            return View();
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult PostBlog()
        {
            var postBlog = new Models.CollectionFontend.PostBlogCollection();
            postBlog.PostStatus = 0; //default 0
            int siteGuid = GetSiteGuid();


            ViewData["IsAdd"] = true;

            //ViewData["ListArticleCategoryDrop"] = new SelectList(GetListArticleCategoryDropBasic(null, null, null, null, null, null, null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid, null), "CategoriesID", "CategoriesName");


            return PartialView("../BaseFontend/" + GetSiteGuid() + "/PostBlog", postBlog);
        }

        //[CaptchaValidator]
        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult PostBlog(FormCollection collection)//, bool captchaValid)
        {
            BaseService baseSvc = new BaseService();
            var postBlog = new Models.CollectionFontend.PostBlogCollection();
            TryUpdateModel(postBlog);
            int postID = 0;
            try
            {
                //if (captchaValid)//success captcha
                //{
                 if (Session["Captcha"] == null || Session["Captcha"].ToString() != postBlog.Captcha)
                 {
                        ModelState.AddModelError("Captcha", "Kết quả sai.Xin vui lòng thử lại.");
                        //dispay error and generate a new captcha
                        ViewData["Result"] = "Xin vui lòng nhập kết quả.";
                        return PartialView("../BaseFontend/" + GetSiteGuid() + "/PostBlog", postBlog);
                  }
                  else
                  {
                    //if (article.ArrayArticleCategoryID != "" && article.ArrayArticleCategoryID != null)
                    //{
                    //Create PostBlog
                    SCSService.Post post = new Post();
                    post.PostTitle = postBlog.PostTitle;
                    post.PostAbstract = postBlog.PostAbstract;
                    post.PostContent = postBlog.PostContent;
                    post.PostCreat = DateTime.Now;
                    post.PostUser = int.Parse(Session["UserID"].ToString());
                    post.PostLink = postBlog.PostLink;
                    post.PostImage = postBlog.PostImage;
                    post.AttachFile = postBlog.AttachFile;
                    post.PostStatus = postBlog.PostStatus;
                    post.PostSource = postBlog.PostSource;
                    post.Title = postBlog.Title;
                    post.MetaKeyword = postBlog.MetaKeyword;
                    post.MetaDesciption = postBlog.MetaDesciption;

                    postID = Models.ModelsFontend.PostModel.CreatePost(post);

                    if (postID > 0)
                    {
                        //var arr = article.ArrayArticleCategoryID.ToString().Split(',');
                        //foreach (var item in arr)
                        //{
                        //    //Add Article to Article_Frontpage
                        //    SCSService.Article_Frontpage front = new Article_Frontpage();
                        //    front.ArticleID = artID;
                        //    front.CategoriesID = int.Parse(item);

                        //    Models.ArticaleMasterModel.CreateArticleFrontpage(front);
                        //}
                        if(GetSiteGuid()==24)
                        {
                            SCSService.Post_In_Category pi = new Post_In_Category();
                            pi.CategoryID=6;
                            pi.PostID = postID;
                            pi.CreateDate = DateTime.Now;

                            Models.ModelsFontend.PostModel.CreatePostInCategory(pi);
                        }
                        

                        ViewData["Result"] = "Chúng tôi đã nhận được bài viết của bạn. Bài viết này sẽ được hiển thị sau khi quản trị viên của chúng tôi tiếp nhận.";
                    }


                    return PartialView("../BaseFontend/" + GetSiteGuid() + "/PostBlog", postBlog);
                    //}
                    //else
                    //{
                    //    ViewData["Result"] = "Please Choice Article Category !";
                    //    return View("DetailArticle", article); //return Detail Article
                    //}
                }
                

            }
            catch
            {
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/PostBlog", postBlog);
            }

        }

        #endregion

    }
}
